package com.timmy.google_play.base;

import android.support.annotation.NonNull;
import android.support.v4.view.ViewCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.AdapterView;
import android.widget.ListView;

import com.timmy.google_play.factory.ThreadPoolProxyFactory;
import com.timmy.google_play.holder.LoadMoreHolder;

import java.util.List;

/**
 * Created by Timmy on 2016/12/8.
 */

public abstract class SuperBaseAdapter<T> extends MyBaseAdapter<T> implements AdapterView.OnItemClickListener {

    public static final int VIEWTYPE_LOADMORE = 0;
    public static final int VIEWTYPE_NORMAL   = 1;
    private final ListView       mListView;
    private       LoadMoreHolder mLoadMoreHolder;
    private       LoadMoreTask   mLoadMoreTask;
    private       int            mState;

    public SuperBaseAdapter(ListView listView, List<T> datas) {
        super(datas);
        mListView = listView;

        listView.setOnItemClickListener(this);
    }

    /**
     * listview中显示几种viewType完成的步骤
     * 1.复写两个方法
     * 2.在getview方法中分别处理
     */
    @Override
    public int getViewTypeCount() {
        return super.getViewTypeCount() + 1;
    }

    @Override
    public int getItemViewType(int position) {

        if (position == getCount() - 1) {
            return VIEWTYPE_LOADMORE;

        } else {
            return getNormalItemViewType(position);
            //            return VIEWTYPE_NORMAL;
        }
    }

    /**
     * 得到普通条目的viewType的类型
     */
    public int getNormalItemViewType(int position) {
        return VIEWTYPE_NORMAL;
    }

    @Override
    public int getCount() {
        return super.getCount() + 1;
    }

    @Override
    public View getView(int position, View converView, ViewGroup viewGroup) {

        //得到当前条目的viewType类型
        int curItemViewType = getItemViewType(position);

        BaseHolder<T> homeHolder = null;

        if (converView == null) {

            if (curItemViewType == VIEWTYPE_LOADMORE) {   //加载更多的类型

                homeHolder = (BaseHolder<T>) getLoadMoreHolder();

            } else {      //普通的listview条目类型

                homeHolder = getSpecialBaseHolder(position);

            }

        } else {
            homeHolder = (BaseHolder<T>) converView.getTag();
        }

        if (curItemViewType == VIEWTYPE_LOADMORE) {         //加载更多的视图应该如何绑定

            if (hasLoadMore()) {
                //有加载更多的数据
                mLoadMoreHolder.setDataAndRefreshHolderView(LoadMoreHolder.LOADMORE_LOADING);

                //如果有更多数据,在这里必须触发加载更多数据
                triggerLoadMoreData();

            } else {
                //没有更多数据
                mLoadMoreHolder.setDataAndRefreshHolderView(LoadMoreHolder.LOADMORE_NONE);

            }
        } else {
            //数据的绑定
            T data = mDatas.get(position);
            homeHolder.setDataAndRefreshHolderView(data);
        }

        View holdView = homeHolder.holdView;

        holdView.setScaleX(0.6f);
        holdView.setScaleY(0.5f);

        ViewCompat.animate(holdView).scaleX(1).scaleY(1).setDuration(400).
                setInterpolator(new OvershootInterpolator(4)).start();

        return holdView;
    }

    /**
     * 触发加载更多数据
     */
    private void triggerLoadMoreData() {
        //异步加载,使用线程池


        if (mLoadMoreTask == null) {

            //重置状态
            mState = LoadMoreHolder.LOADMORE_LOADING;
            mLoadMoreHolder.setDataAndRefreshHolderView(mState);

            mLoadMoreTask = new LoadMoreTask();
            ThreadPoolProxyFactory.getNormalThreadPoolProxy().submit(mLoadMoreTask);
        }
    }

    class LoadMoreTask implements Runnable {

        private static final int PAGERSIZE = 20;

        @Override
        public void run() {

            //定义刷新ui需要的数据
            List<T> loadmoreList = null;

            //得到数据
            try {
                loadmoreList = onLoadMoreData();

                if (loadmoreList != null) {         //加载回来更多的数据
                    int loadmoreSize = loadmoreList.size();
                    if (loadmoreSize < PAGERSIZE) {
                        mState = LoadMoreHolder.LOADMORE_NONE;       //没有加载更多数据
                    } else {
                        mState = LoadMoreHolder.LOADMORE_LOADING;        //有加载更多数据
                    }
                } else {
                    mState = LoadMoreHolder.LOADMORE_NONE;       //没有加载更多数据
                }

            } catch (Exception e) {
                e.printStackTrace();
                mState = LoadMoreHolder.LOADMORE_ERROR;       //加载跟多数据出异常
            }

            //android studio 使用中间变量
            final List<T> finalLoadmoreList = loadmoreList;
            final int     finalState        = mState;
            MyApplication.getHandler().post(new Runnable() {
                @Override
                public void run() {
                    //刷新ui ---> listview 和 加载更多的ui
                    //listview
                    if (finalLoadmoreList != null && finalLoadmoreList.size() > 0) {
                        //更新数据集
                        mDatas.addAll(finalLoadmoreList);
                        notifyDataSetChanged();
                    }

                    mLoadMoreHolder.setDataAndRefreshHolderView(finalState);
                }
            });

            mLoadMoreTask = null;
        }
    }

    /**
     * 在子线程中真正的加载具体的数据
     * <p>
     * 为什么要抛出异常,因为需要用用到异常信息,如果出了异常,说明加载更多数据失败
     * 在superAdapter中不知道具体的实现,交给子类去实现
     * 选择性实现
     */
    public List<T> onLoadMoreData() throws Exception {

        return null;
    }

    /**
     * 是否有加载更多数据
     */
    public boolean hasLoadMore() {
        return false;           //默认没有加载更多的实现,但是子类可以选择性实现是否有加载更多的实现
    }

    @NonNull
    protected abstract BaseHolder<T> getSpecialBaseHolder(int position);

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

        position = position - mListView.getHeaderViewsCount();

        int itemViewType = getItemViewType(position);

        if (itemViewType == VIEWTYPE_LOADMORE) {

            if (mState == LoadMoreHolder.LOADMORE_ERROR) {
                triggerLoadMoreData();
            }
        } else {
            onNormalItemClick(adapterView, view, position, id);
        }
    }

    /**
     * 普通条目的点击时间,需要实现的子类自己去实现
     */
    protected void onNormalItemClick(AdapterView<?> adapterView, View view, int positon, long id) {

    }

    public LoadMoreHolder getLoadMoreHolder() {

        if (mLoadMoreHolder == null) {
            mLoadMoreHolder = new LoadMoreHolder();
        }

        return mLoadMoreHolder;
    }
}
